package com.abe.libcore.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkInfo

object NetWorkUtils {
    //没有连接网络
    const val NETWORK_NONE: Int = -1
    //移动网络
    const val NETWORK_MOBILE: Int = 0
    //无线网络
    const val NETWORK_WIFI: Int = 1

    fun getNetWorkState(mContext: Context): Int {
        // 得到连接管理器对象
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
            val connectivityManager: ConnectivityManager = mContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val activeNetworkInfo = connectivityManager.activeNetworkInfo
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
                if (activeNetworkInfo.type == (ConnectivityManager.TYPE_WIFI)) {
                    return NETWORK_WIFI
                } else if (activeNetworkInfo.type == (ConnectivityManager.TYPE_MOBILE)) {
                    return NETWORK_MOBILE
                }
            } else {
                return NETWORK_NONE;
            }
        } else {
            val connMgr: ConnectivityManager = mContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            //获取所有网络连接的信息
            val networks: Array<Network> = connMgr.allNetworks
            //通过循环将网络信息逐个取出来
            for (work: Network in networks) {
                //获取ConnectivityManager对象对应的NetworkInfo对象
                val networkInfo: NetworkInfo = connMgr.getNetworkInfo(work)
                if (networkInfo.isConnected) {
                    if (networkInfo.type == ConnectivityManager.TYPE_MOBILE) {
                        return NETWORK_MOBILE
                    } else {
                        return NETWORK_WIFI
                    }
                }
            }
        }
        return NETWORK_NONE
    }
}